package com.bnlr.lrparking.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.login.ForgetPassWordActivity;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.effects.BaseEffects;
import com.bnlr.lrparking.effects.Effectstype;
import com.bnlr.lrparking.model.VerifyCodeM;
import com.bnlr.lrparking.reserve.ExampleUtil;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONObject;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by Administrator on 2017/6/6.
 */

public class LoginDialog extends Dialog implements View.OnClickListener {
    private Context context;

    public LoginDialog(Context context) {
        super(context, R.style.NativeDialog);
        this.context = context;
        initView();
    }

    View mView;
    RelativeLayout close;
    RelativeLayout rela_pawlogin;
    TextView tv_login_pwd, tv_tophone_login, tv_register_yzm, tv_login_miss_pwd, login_xieyi;
    TextView tv_register;//注册
    LinearLayout lay_loginyzm, lay_loginpsw, lay_login_phone;
    EditText et_register_phone, et_register_yzm, et_register_password;
    Effectstype type;
    String mobile, et_yzm, password;
    String yzm = "";
    Button btn_login;
    CheckBox checkbox_reg_xieyi;
    private CountDownTimer time;

    private void initView() {
        mView = LayoutInflater.from(getContext()).inflate(R.layout.doalog_login, null);
        close = (RelativeLayout) mView.findViewById(R.id.raly_close);
        lay_loginyzm = (LinearLayout) mView.findViewById(R.id.lay_loginyzm);
        lay_loginpsw = (LinearLayout) mView.findViewById(R.id.lay_loginpsw);
        lay_login_phone = (LinearLayout) mView.findViewById(R.id.lay_login_phone);
        tv_login_pwd = (TextView) mView.findViewById(R.id.tv_login_pwd);
        rela_pawlogin = (RelativeLayout) mView.findViewById(R.id.rela_pawlogin);
        tv_register = (TextView) mView.findViewById(R.id.tv_register);
        tv_login_miss_pwd = (TextView) mView.findViewById(R.id.tv_login_miss_pwd);
        tv_tophone_login = (TextView) mView.findViewById(R.id.tv_tophone_login);
        tv_register_yzm = (TextView) mView.findViewById(R.id.tv_register_yzm);
        login_xieyi = (TextView) mView.findViewById(R.id.login_xieyi);
        et_register_phone = (EditText) mView.findViewById(R.id.et_register_phone);
        et_register_password = (EditText) mView.findViewById(R.id.et_register_password);
        et_register_yzm = (EditText) mView.findViewById(R.id.et_register_yzm);
        checkbox_reg_xieyi = (CheckBox) mView.findViewById(R.id.checkbox_reg_xieyi);
        btn_login = (Button) mView.findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);
        tv_login_pwd.setOnClickListener(this);
        tv_register.setOnClickListener(this);
        tv_login_miss_pwd.setOnClickListener(this);
        tv_tophone_login.setOnClickListener(this);
        login_xieyi.setOnClickListener(this);
        close.setOnClickListener(this);
        tv_register_yzm.setOnClickListener(this);
        //初始化计时器
        time = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                //计时过程显示
                tv_register_yzm.setEnabled(false);
                tv_register_yzm.setText(millisUntilFinished / 1000 + "秒后重发");
                tv_register_yzm.setBackgroundResource(R.drawable.rec_redbag_white);
                tv_register_yzm.setTextColor(context.getResources().getColor(R.color.write));
            }

            @Override
            public void onFinish() {
                //计时结束
                onTimeCancle();
            }
        };
        super.setContentView(mView);
    }

    //计时器结束，重新获取
    private void onTimeCancle() {
        tv_register_yzm.setText("重新获取");
        tv_register_yzm.setEnabled(true);
        tv_register_yzm.setBackgroundResource(R.drawable.rec_bg_stroke_main01);
        tv_register_yzm.setTextColor(context.getResources().getColor(R.color.main_color));
    }

    @Override
    public void setContentView(int layoutResID) {
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
    }

    @Override
    public void setContentView(View view) {
    }

    @Override
    public void show() {
        super.show();
        Window dialogWindow = this.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        /////////获取屏幕宽度
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        ;
        wm.getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        /////////设置高宽
        lp.width = (int) (screenWidth * 0.85); // 宽度
        dialogWindow.setAttributes(lp);
    }

    BaseEffects animator;
    private int login_way = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_xieyi:
                Intent intent = new Intent(context, WebActivity.class);
                intent.putExtra("tag", 6);
                context.startActivity(intent);
                break;
            case R.id.tv_login_pwd:
                login_way = 1;
                type = Effectstype.Fliph;
                mView.setVisibility(View.VISIBLE);
                animator = type.getAnimator();
                animator.setDuration(Math.abs(500));
                animator.start(mView);
                lay_loginyzm.setVisibility(View.GONE);
                rela_pawlogin.setVisibility(View.GONE); //////////////////
                tv_register_yzm.setVisibility(View.GONE);
                lay_loginpsw.setVisibility(View.VISIBLE);
                lay_login_phone.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_register:
                LoginDialog.this.dismiss();
                intent = new Intent(context, ForgetPassWordActivity.class);
                intent.putExtra("msg", "register");
                context.startActivity(intent);
                break;
            case R.id.tv_tophone_login:
                login_way = 0;
                type = Effectstype.FlipR;
                mView.setVisibility(View.VISIBLE);
                animator = type.getAnimator();
                animator.setDuration(Math.abs(500));
                animator.start(mView);
                lay_loginyzm.setVisibility(View.VISIBLE);
                rela_pawlogin.setVisibility(View.VISIBLE);
                tv_register_yzm.setVisibility(View.VISIBLE);
                lay_loginpsw.setVisibility(View.GONE);
                lay_login_phone.setVisibility(View.GONE);
                break;
            case R.id.raly_close:
                LoginDialog.this.dismiss();
                break;
            case R.id.tv_register_yzm:
                mobile = et_register_phone.getText().toString();
                if (TextUtils.isEmpty(mobile)) {
                    CommonUtil.showToask(context, "请输入用户手机号");
                    return;
                }
                if (!CommonUtil.isMobileNO(mobile)) {
                    CommonUtil.showToask(context, "手机号格式不正确");
                    return;
                }
                SendYzm();
                break;
            case R.id.btn_login:
                mobile = et_register_phone.getText().toString().trim();
                et_yzm = et_register_yzm.getText().toString().trim();
                password = et_register_password.getText().toString().trim();
                if (TextUtils.isEmpty(mobile)) {
                    CommonUtil.showToask(context, "请填写正确的手机号码!");
                    return;
                } else if (!CommonUtil.isMobileNO(mobile)) {
                    CommonUtil.showToask(context, "手机号码格式错误!");
                    return;
                }
                if (login_way == 0) {
                    if (!et_yzm.equals(yzm)) {
                        CommonUtil.showToask(context, "验证码错误!");
                        return;
                    }
                } else if (login_way == 1) {
                    if (TextUtils.isEmpty(password)) {
                        CommonUtil.showToask(context, "密码不能为空!");
                        return;
                    } else if (CommonUtil.isContainChinese(password)) {
                        CommonUtil.showToask(context, "密码格式错误!");
                        return;
                    } else if (password.length() < 6 || password.length() > 16) {
                        CommonUtil.showToask(context, "密码长度6~16");
                        return;
                    }
                }
                if (!checkbox_reg_xieyi.isChecked()) {
                    CommonUtil.showToask(context, "请阅读并接收《利人停车使用协议》");
                    return;
                }
                Login();
                break;
            case R.id.tv_login_miss_pwd:
                LoginDialog.this.dismiss();
                intent = new Intent(context, ForgetPassWordActivity.class);
                intent.putExtra("msg", "findpwd");
                context.startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void Login() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "Login");
            mRequest.add("type", login_way);
            mRequest.add("phone", mobile);
            if (login_way == 1) {
                mRequest.add("pwd", password);
            } else {
                mRequest.add("pwd", "");
            }
            // 添加到请求队列
            CallServer.getRequestInstance().add(context, mRequest,
                    new CustomHttpListener<VerifyCodeM>(context, true, VerifyCodeM.class) {
                        @Override
                        public void doWork(VerifyCodeM data, String code) {

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    CommonUtil.showToask(context, "登录成功");
                                    AppConfig.getInstance().putBoolean("isLogin", true);
                                    AppConfig.getInstance().putString("uid", obj.getJSONObject("data").getString("uid"));
//                                    setAlias(AppConfig.getInstance().getString("uid", ""));
                                    setAlias(mobile);
                                    LoginDialog.this.dismiss();
                                } else {
                                    CommonUtil.showToask(context, obj.getString("msg"));
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                time.cancel();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }


    }

    /**
     * 网络请求对象.
     */
    public Request<String> mRequest;

    private void SendYzm() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "sendValidateMCD");
            mRequest.add("phone", mobile);
            mRequest.add("flag", "0");
            // 添加到请求队列
            CallServer.getRequestInstance().add(context, mRequest,
                    new CustomHttpListener<VerifyCodeM>(context, true, VerifyCodeM.class) {
                        @Override
                        public void doWork(VerifyCodeM data, String code) {

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {//{"msgcode":"1","msg":"成功","data":{"code":"06641"}}
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    time.start();
                                    yzm = obj.getJSONObject("data").getString("code");
                                } else {
                                    CommonUtil.showToask(context, obj.getString("msg"));
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                time.cancel();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    // **************************设置标签**************************
    public void setAlias(String alias) {

        // 调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:

                    JPushInterface.setAliasAndTags(context.getApplicationContext(),
                            (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:

                    JPushInterface.setAliasAndTags(context.getApplicationContext(), null,
                            (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
            }
        }
    };

    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    CommonUtil.showToask(context.getApplicationContext(), "设置成功");
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    CommonUtil.showToask(context.getApplicationContext(), "设置失败");
                    if (ExampleUtil.isConnected(context.getApplicationContext())) {
                        mHandler.sendMessageDelayed(
                                mHandler.obtainMessage(MSG_SET_TAGS, tags),
                                1000 * 60);
                    } else {

                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;

            }
            LogUtils.d("TagAliasCallback", logs);
//            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    // PromptManager.showToast(getApplicationContext(), "设置成功");
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    // PromptManager.showToast(getApplicationContext(), "设置失败");
                    if (ExampleUtil.isConnected(context.getApplicationContext())) {
                        mHandler.sendMessageDelayed(
                                mHandler.obtainMessage(MSG_SET_ALIAS, alias),
                                1000 * 60);
                    } else {

                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;

            }
            LogUtils.d("TagAliasCallback", logs);
//            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };
}
